from whoosh.qparser import QueryParser
from whoosh.index import open_dir
from whoosh import scoring
from config import INDEX_DIR, SEARCH_RESULT_LIMIT


def search():
    print("欢迎使用联行号搜索:")
    print("q", "退出搜索")
    ix = open_dir(INDEX_DIR)
    searcher = ix.searcher(weighting=scoring.TF_IDF())
    query_parser = QueryParser('content', schema=ix.schema)
    while True:
        text = input("请输入关键字：")
        text = text.strip()
        if not text:
            continue
        elif text == "q" or text == "Q":
            ix.close()
            break
        else:
            # 解析查询语句
            query = query_parser.parse(text)
            results = searcher.search(query, limit=SEARCH_RESULT_LIMIT)
            if not results:
                print("暂无数据")
            else:
                index = 0
                for r in results:
                    index += 1
                    content = r['content'].ljust(40, "　")
                    print(str(index).ljust(3), content, r['code'])
